<template>
  <div class="manage">
    <div class="manage-header">
      <!-- 新增按钮 -->
      <el-button type="primary" @click="handlecreate">+ 新增</el-button>

      <!-- 对话框:点击新增或编辑才会弹出表单 -->
      <!-- :before-close="closeDialog" 点击关闭的x之前要做的事情 -->
      <el-dialog :title="modalType == 0 ? '新建' : '编辑'" :visible.sync="dialogVisible" width="50%"
        :before-close="closeDialog">
        <!-- 表单Form -->
     <img v-show="modalType == 1"  :src="imgurl"  width="100%" height="100%">
        <!-- ref=form:为了通过this.$refs调用组件的方法 -->
        <el-upload v-if="modalType == 0" style="margin-left:14%;margin-top:5%"
                   class="avatar-uploader el-upload--text"
                   :drag="1===1"
                   action="http://localhost:8080/up/img"
                   multiple
                   :show-file-list="false"
                   :data="{SavePath: this.Path.url}"
                   :on-success="handleVideoSuccess"
                   :before-upload="beforeUploadVideo"
                   :on-progress="uploadVideoProcess">
          <i v-if="Plus" class="el-icon-upload"></i>
          <div v-if="Plus" class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <el-progress v-if="videoFlag" type="circle" :percentage="videoUploadPercent" style="margin-top:30px;"></el-progress>
          <div class="el-upload__tip" slot="tip">只能上传png/jpf/gif文件，且不超过300M</div>
        </el-upload>

        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 搜索框 -->
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="searchForm.sername" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="common-table" style="height:80vh">
      <!-- 用户数据Table -->
      <el-table :data="tableData" stripe style="width: 100%" height="100%">
        <el-table-column prop="id" label="ID" min-width="10%">
        </el-table-column>
        <el-table-column prop="sername" label="名称" min-width="16%">
        </el-table-column>
        <el-table-column prop="addr" label="地址" min-width="16%">
        </el-table-column>
        <el-table-column prop="size" label="大小" min-width="16%">
        </el-table-column>
        <el-table-column prop="ischeck" label="是否识别" min-width="16%">
        </el-table-column>
        <!-- 自定义列 -->
        <el-table-column label="操作" min-width="22%">
          <template slot-scope="scope">
            <el-button @click="handleEdit(scope.row)">打开</el-button>
            <el-button @click="down(scope.row)">下载</el-button>
            <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pager">
        <el-pagination
            :page-size="10"
            :pager-count="11"
            layout="prev, pager, next"
            :total="total"
            @current-change="currentChange"
        >
        </el-pagination>
      </div>



    </div>
  </div>
</template>
  
<script>
import {deleteimg, getImgList} from "@/api";

export default {
  // eslint-disable-next-line vue/multi-word-component-names

  data() {
    return {
      // 表单绑定的数据
      form: {
        id : '',
        name: '',
        addr: '',
        size: '',
        ischeck: ''
      },
        imgurl:'',
      // 表单验证规则
      // 表单是否打开
      dialogVisible: false,
      // 列表数据
      tableData: [],
      // 打开表单:新建0,编辑1
      modalType: 0,
      // 分页的对象
      pageData: {
        pageNum: 1,
        pageSize: 10
      },
      // 分页页数
      total: 0,
      // 搜索框表单
      searchForm: {
        sername: ''
      },
      videoForm: {
        videoId: '',
        videoUrl: ''
      },
      videoFlag: false,
      Plus: true,
      Path: {
        url: 'D:/img/images'
      },
      videoUploadPercent: 0
    }
  },
  methods: {
    down(row){

      var form = document.createElement("form");//创建form元素
      form.setAttribute("style", "display:none");
      form.setAttribute("method", "post");//post方式提交
      var input = document.createElement('input');//用input标签传递参数
      input.setAttribute('type', 'hidden');
      input.setAttribute('name', 'name');
      input.setAttribute('value', row.name);
      form.append(input);
      var input2 = document.createElement('input');
      input2.setAttribute('name', 'addr');
      input2.setAttribute('value', row.addr);
      form.append(input2);
      form.setAttribute("action", "http://localhost:8080/up/down");//请求地址
      form.setAttribute("target", "_self");//不跳转至新页面
      var body = document.createElement("body");
      body.setAttribute("style", "display:none");
      document.body.appendChild(form);
      form.submit();
      form.remove();
    },
    // 获取列表数据
    getList() {
      // 由接口文档知传入一个对象:要返回的是当前页面数据和搜索到的数据的交集
  getImgList({params: { ...this.pageData ,...this.searchForm} }).then(data => {
  this.tableData = data.data.data.list
  this.total = data.data.data.total|| 0
  console.log(this.tableData)
})
    },
    // 表单提交
    submit() {
      // 要用箭头函数,若用function会报错,不知道为什么
this.closeDialog()
    },
    // 关闭对话框
    closeDialog() {
      // 先重置
     this.imgurl=''
      // 后关闭
      this.dialogVisible = false
    },
    // 编辑按钮
    handleEdit(index) {
      this.modalType = 1
      this.openForm()
      this.imgurl='http://localhost:9091/images/'+index.name
      console.log(this.imgurl)
      // 深拷贝
      this.form = JSON.parse(JSON.stringify(index))
    },
    // 删除按钮
    handleDelete(index) {
      this.$confirm('此操作将永久删除该照片, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除操作:根据后端接口,参数是对象,id是唯一标识符
        deleteimg({params:{id:index.id}}).then((data) => {
          if(data.data.code === 200){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }else{
            this.$message.error("删除失败")
          }
        })
      }).catch(() => {
        // 点击取消:不删除了
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 新建按钮
    handlecreate() {
      this.modalType = 0
      this.openForm()
    },
    // 打开表单
    openForm() {
      this.dialogVisible = true
    },
    // 改变页码
    currentChange(val) {
      this.pageData.pageNum = val
      this.getList()
    },
    // 搜索
    search() {
      this.getList()
    },
    beforeUploadVideo (file) {
      const isLt300M = file.size / 1024 / 1024 < 300
      if (['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'].indexOf(file.type) === -1) {
        this.$message.error('请上传正确的图片格式');
        return false;
      }
      if (!isLt300M) {
        this.$message.error('上传图片大小不能超过300MB哦!')
        return false
      }
    },
    // 上传过程中执行
    uploadVideoProcess (event, file) {
      this.Plus = false
      this.videoFlag = true
      this.videoUploadPercent = file.percentage.toFixed(0)
    },
    // 上传成功是执行
    handleVideoSuccess (res) {
      this.Plus = false
      this.videoUploadPercent = 100
      console.log(res)

      // 如果为200代表保存成功
      if (res.resCode === '200') {
        // 接收传回来的名称和保存地址
        this.videoForm.videoId = res.newVidoeName
        this.videoForm.videoUrl = res.VideoUrl
        this.$message.success('上传成功！')
        //this.videoFlag=false
        this.videoUploadPercent=0;
      } else {
        this.$message.error('上传失败，请重新上传！')
      }
      this.getList()
    }
  },
  mounted() {
    this.getList()
  }
}
</script>
  
<style lang="less" scoped>
.manage {
  height: 100%;

  .manage-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .common-table {
    height: 90%;
    position: relative;

    .pager {
      position: absolute;
      right:45%;
      bottom: 0px;
    }
  }
}
</style>